package v3

import (
	"crypto"
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/base64"
	"encoding/pem"
	"errors"
	mrand "math/rand"
	"strings"
	"time"
)

const (
	PemBegin = "-----BEGIN RSA PRIVATE KEY-----\n"
	PemEnd   = "\n-----END RSA PRIVATE KEY-----"
)

func rsaSign(content, privateKey string, hash crypto.Hash) string {
	shaNew := hash.New()
	shaNew.Write([]byte(content))
	hashed := shaNew.Sum(nil)
	priKey, err := parsePrivateKey(privateKey)
	if err != nil {
		panic(err)
	}
	signature, err := rsa.SignPKCS1v15(rand.Reader, priKey, hash, hashed)
	if err != nil {
		panic(err)
	}
	return base64.StdEncoding.EncodeToString(signature)
}

func parsePrivateKey(privateKey string) (*rsa.PrivateKey, error) {
	privateKey = formatPrivateKey(privateKey)
	block, _ := pem.Decode([]byte(privateKey))
	if block == nil {
		return nil, errors.New("私钥信息错误！")
	}
	priKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	return priKey, nil
}

func formatPrivateKey(privateKey string) string {
	if !strings.HasPrefix(privateKey, PemBegin) {
		privateKey = PemBegin + privateKey
	}
	if !strings.HasSuffix(privateKey, PemEnd) {
		privateKey = privateKey + PemEnd
	}
	return privateKey
}

const randSource string = "adcdefghjkmnpqrstuvwxyz1234567890ABCDEFGHJKLMNPQRSTUVWXYZ9876543210"

const slen = len(randSource)

func init() {
	mrand.Seed(time.Now().UnixNano())
}

// 生成指定位数的随机字符串
func genRandStr(bits int) string {
	builder := strings.Builder{}
	for i := 0; i < bits; i++ {
		intn := mrand.Intn(slen)
		builder.WriteByte(randSource[intn])
	}
	return builder.String()
}
